#!/bin/bash
# Author: Steven Shiau <steven _at_ clonezilla org>
# License: GPL

# Load DRBL setting and functions
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Load keymap if it exists
[ -e /etc/ocs/ocs-live.conf ] && . /etc/ocs/ocs-live.conf

# Since now the DRBL live startup service is in rc2.d, no need to use bterm anymore.
## A workaround here... Since jfbterm exits with segfault in rcS.d in Debian booting, we force to use "bterm" here.
fb_term=""
get_fb_term
#fb_term="bterm"
[ "$fb_term" = "bterm" -a ! -e "$uni_font" ] && exit 1

export LANG="en_US.UTF-8"
gen_locale_if_not_found en_US en_US.UTF-8

echo "Configuring keyboard..."
# ocs_live_keymap and live_keyboard_layouts are loaded from ocs-live.conf
if [ -z "$live_keyboard_layouts" ]; then
  # keymap not set in ocs-live.conf, use interactive dialog to set it.
  # Bterm/jfbterm/fbterm can only be used (it's better since Asian fonts can be shown) when:
  # (1) If bterm and uni fonts or jfbterm are available
  # (2) If it's not in serial console
  # (3) frambebuffer device exists
  if [ -n "$fb_term" -a -z "$(grep -E "console=.*ttyS.*" /proc/cmdline)" ] && \
     ([ -e /dev/fb/0 ] || [ -e /dev/fb0 ]); then 
    case "$fb_term" in
      "bterm")
         export TERM=bterm
         set +e
         # bterm need full path command even it's in the PATH already.
         bterm -l $LANG -f $uni_font `command -v ocs-langkbdconf-bterm`
         set -e
         ;;
      "jfbterm")
         export TERM=jfbterm
         set +e
         jfbterm -q -e ocs-langkbdconf-bterm
         set -e
         ;;
      "fbterm")
         export TERM=fbterm
         set +e
         fbterm -- ocs-langkbdconf-bterm
         set -e
         ;;
    esac
  else
    # ocs-langkbdconf-bterm does keyboard config and language config. Here we have do the same 2 jobs. Otherwise locales will be empty and a lot of warnings will be shown when ruuning commands.
    # (1) language
    [ -z "$ocs_lang" ] && ocs_lang=en_US.UTF-8
    # put the language setting so that later program can reuse
    if [ -z "$(grep -E "^[[:space:]]*ocs_lang=" /etc/ocs/ocs-live.conf 2>/dev/null)" ]; then
      # append it
      echo "ocs_lang=$ocs_lang" >> /etc/ocs/ocs-live.conf
    else
      # modify it
      perl -pi -e "s|^[[:space:]]*ocs_lang=.*|ocs_lang=\"$ocs_lang\"|g" /etc/ocs/ocs-live.conf
    fi
    # (2) keyboard
    drbl-kbdchooser
  fi
fi

# Varialble ocs_lang will be created in ocs-langkbdconf-bterm, and write to /etc/ocs/ocs-live.conf.
# Load ocs_lang if it exists
[ -e /etc/ocs/ocs-live.conf ] && . /etc/ocs/ocs-live.conf
if [ -n "${ocs_lang}" ]; then
  echo "Setting locale in /etc/default/locale... "
  cat <<-LOCALE_END > /etc/default/locale
LC_ALL="${ocs_lang}"
LANG="${ocs_lang}"
LOCALE_END
fi
